package uk.ac.nott.cs.g53dia;

import java.util.List;

import uk.ac.nott.cs.g53dia.bee.BeeYieldApproximator;
import utils.Constants;

public class CommunicateAction implements Action {

  public static final int DANCE_FLOWER_POSITIONS = 0;
  public static final int DANCE_FLOWER_SAMPLES = 1;

  public static final int COMMUNICATION_RANGE = 0;
  public static final int MIN_PRICE = 2;
  public static final int MAX_POSITIONS_PRICE = 30;
  public static final int MAX_SAMPLES_PRICE = 10;
  public static final int DELAY_PERIOD = 5;
  
  private int type;

  public CommunicateAction(int type) {
    this.type = type;
  }

  public void execute(Environment env, Bee bee) throws ActionFailedException {
    List<Bee> beesInRange = env.getBeesForCommunication(bee.getPosition(), COMMUNICATION_RANGE);
    beesInRange.remove(bee); // myself
    if (Constants.DEBUG)
      System.out.println("bee " + bee.getId() + " is communicating");
    if (beesInRange.size() == 0) {
      bee.useEnergy(1);
      throw new ActionFailedException("No bees to communicate with");
    } else if (type == DANCE_FLOWER_POSITIONS) {
      int max = 0;
      for (Bee otherBee : beesInRange) {
        int price = otherBee.updateFlowersPositions(bee.getFlowersOfType());
        if (price > max) {
          max = price;
        }
        otherBee.addCells(bee.getCells());
      }
      bee.useEnergy(max);
    } else if (type == DANCE_FLOWER_SAMPLES) {
      int max = 0;
      for (Bee otherBee : beesInRange) {
        int price = otherBee.updateFlowersYields(bee.getSamples());
        if (price > max) {
          max = price;
        }
        bee.communicate(otherBee);
      }
      bee.useEnergy(max);
    }
  }

  public String toString() {
    return "Communicate " + type;
  }

  public String getCode() {
    return String.valueOf(Constants.COMMUNICATE_ACTION_CODE + Constants.ACTION_ARGS_SEPARATOR + type);
  }
}
